#!/bin/bash
set -euo pipefail
trap 'echo -e "\033[31m操作被中断\033[0m"; exit 130' INT TERM

# 日志函数
log() {
    local level=$1
    shift
    echo -e "$(date '+%F %T') [${level}] $*"
}

log info "正在停止防火墙"
sudo systemctl stop firewalld || {
    log warn "防火墙停止失败，继续执行"
}

mount_point="/mount"
if ! findmnt -M "$mount_point" &>/dev/null; then
    log info "创建挂载目录"
    sudo mkdir -p "$mount_point"
    
    log info "挂载ISO镜像"
    if ! sudo mount /dev/sr0 "$mount_point"; then
        log error "ISO挂载失败，请检查光盘设备"
        exit 1
    fi
else
    log info "ISO已挂载，跳过挂载步骤"
fi

repo_file="/etc/yum.repos.d/rhel9.repo"
log info "生成YUM仓库文件"
sudo tee "$repo_file" <<EOF
[BaseOS]
name=rhel9-BaseOS
baseurl=file://${mount_point}/BaseOS
gpgcheck=0

[Appstream]
name=rhel9-Appstream
baseurl=file://${mount_point}/AppStream
gpgcheck=0
EOF

log info "清理YUM缓存"
sudo yum clean all
sudo yum makecache

log success "YUM仓库配置完成"
echo "YUM仓库配置已生成至 $$REPO_FILE"